﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Shileme.Common.Helper
{
    public class ImageHelper
    {
        #region GetPicThumbnail
        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="dHeight">高度</param>
        /// <param name="dWidth"></param>
        /// <param name="flag">压缩质量 1-100</param>
        /// <returns></returns>

        public static bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag)
        {
            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);

            ImageFormat tFormat = iSource.RawFormat;

            int sW = 0, sH = 0;

            //按比例缩放

            Size tem_size = new Size(iSource.Width, iSource.Height);



            if (tem_size.Width > dHeight || tem_size.Width > dWidth) //将**改成c#中的或者操作符号
            {

                if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
                {

                    sW = dWidth;

                    sH = (dWidth * tem_size.Height) / tem_size.Width;

                }

                else
                {

                    sH = dHeight;

                    sW = (tem_size.Width * dHeight) / tem_size.Height;

                }

            }

            else
            {

                sW = tem_size.Width;

                sH = tem_size.Height;

            }

            Bitmap ob = new Bitmap(dWidth, dHeight);

            Graphics g = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);

            g.CompositingQuality = CompositingQuality.HighQuality;

            g.SmoothingMode = SmoothingMode.HighQuality;

            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

            g.Dispose();

            //以下代码为保存图片时，设置压缩质量

            EncoderParameters ep = new EncoderParameters();

            long[] qy = new long[1];

            qy[0] = flag;//设置压缩的比例1-100

            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);

            ep.Param[0] = eParam;

            try
            {

                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();

                ImageCodecInfo jpegICIinfo = null;

                for (int x = 0; x < arrayICI.Length; x++)
                {

                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {

                        jpegICIinfo = arrayICI[x];

                        break;

                    }

                }

                if (jpegICIinfo != null)
                {

                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径

                }

                else
                {

                    ob.Save(dFile, tFormat);

                }

                return true;

            }

            catch
            {

                return false;

            }

            finally
            {

                iSource.Dispose();

                ob.Dispose();

            }



        }



        /// <summary>
        /// 验证图片格式
        /// </summary>
        /// <param name="fileExtension"></param>
        public static bool ValiImageExt(string fileExtension)
        {
            string[] imageExts = { "jpg", "bmp", "png" };
            foreach (var item in imageExts)
            {
                if (fileExtension.ToLower() == item)
                {
                    return true;
                }
            }
            return false;
        }


        public static string GetPicWidth(HttpPostedFileBase UpFile)
        {

            Byte[] FileByteArray = new byte[UpFile.ContentLength];
            Stream StreamObject = UpFile.InputStream;
            StreamObject.Read(FileByteArray, 0, UpFile.ContentLength);
            string Base64String = ByteToBase64(FileByteArray, 0, FileByteArray.Length);

            System.Drawing.Image myImage = System.Drawing.Image.FromStream(StreamObject);
            return CheckImage(Convert.ToInt32(myImage.Width), Convert.ToInt32(myImage.Height));
        }

        public static string CheckImage(int Width, int Height)
        {
            string result = "1";
            int minwidth = 100, minheight = 50;//图片尺寸宽不得小于100PX 高不得小于50PX！
            if (Width< minwidth || Height< minheight)
            {
              
                result = "100";
            }

            int maxwidth = 1500, maxheight = 1500;//抱歉,上传失败，图片尺寸宽不得大于1500PX,高不得大于1500PX
            if (Width > maxwidth || Height > maxheight)
            {
                result = "700";
            }
            return result;
        }
        //这里是进行二进制到Base64的转换
        private static string ByteToBase64(byte[] ByteArry, int Start, int Length)
        {
            string Result;
            Result = System.Convert.ToBase64String(ByteArry, Start, Length);
            return Result;
        }



        public enum ValidateImageResult { OK=1, InvalidFileSize=2, InvalidImageSize=2 }

        /// <summary>
        /// 图片检测
        /// </summary>
        /// <param name="file"></param>
        /// <param name="MAX_FILE_SIZE"></param>
        /// <param name="MAX_WIDTH"></param>
        /// <param name="MAX_HEIGHT"></param>
        /// <returns></returns>
        public static ValidateImageResult ValidateImage(string file, int MAX_FILE_SIZE, int MAX_WIDTH, int MAX_HEIGHT,int min_width,int min_height)
        {
            byte[] bs = File.ReadAllBytes(file);

            double size = (bs.Length / 1024);
            //大于50KB 
            if (size > MAX_FILE_SIZE) return ValidateImageResult.InvalidFileSize;
            Image img = Image.FromFile(file);
            if (img.Width > MAX_WIDTH || img.Height > MAX_HEIGHT) return ValidateImageResult.InvalidImageSize;
            if (img.Width < min_width || img.Height < min_height)//图片不能小于100*100
            {
                return ValidateImageResult.InvalidImageSize;
            }
            img.Dispose();
            return ValidateImageResult.OK;
        }

        /// <summary>
        /// 图片检测
        /// </summary>
        /// <param name="file"></param>
        /// <param name="MAX_FILE_SIZE"></param>
        /// <param name="MAX_WIDTH"></param>
        /// <param name="MAX_HEIGHT"></param>
        /// <returns></returns>
        public static ValidateImageResult ValidateImage(HttpPostedFileBase UpFile, int MAX_FILE_SIZE, int MAX_WIDTH, int MAX_HEIGHT, int min_width, int min_height)
        {

            Byte[] FileByteArray = new byte[UpFile.ContentLength];
            Stream StreamObject = UpFile.InputStream;
            StreamObject.Read(FileByteArray, 0, UpFile.ContentLength);
            string Base64String = ByteToBase64(FileByteArray, 0, FileByteArray.Length);

            double size = (FileByteArray.Length / 1024);
            //大于50KB 
            if (size > MAX_FILE_SIZE) return ValidateImageResult.InvalidFileSize;
            System.Drawing.Image img = System.Drawing.Image.FromStream(StreamObject);
            if (img.Width > MAX_WIDTH || img.Height > MAX_HEIGHT) return ValidateImageResult.InvalidImageSize;
            if (img.Width < min_width || img.Height < min_height)//图片不能小于100*100
            {
                return ValidateImageResult.InvalidImageSize;
            }
            img.Dispose();
            return ValidateImageResult.OK;
        }

        #endregion
    }
}
